package cn.unknownerror.ueteam.listener;

import cn.unknownerror.ueteam.data.ConfigurationManager;
import cn.unknownerror.ueteam.event.CreateTeamEvent;
import cn.unknownerror.ueteam.event.JoinTeamEvent;
import cn.unknownerror.ueteam.event.LeaveTeamEvent;
import cn.unknownerror.ueteam.team.AbstractTeam;
import cn.unknownerror.ueteam.team.ITeam;
import cn.unknownerror.ueteam.team.TeamAPI;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class PrefixListener implements Listener {
    private static String prefix;
    private static Map<UUID,String> map;

    public PrefixListener(ConfigurationManager config) {
        prefix = config.getConfig().getString("Team.Chatting.prefix").replaceAll("&","§");
        map=new HashMap<>();
    }

    @EventHandler
    public void onJoin(PlayerJoinEvent event) {
        ITeam team = TeamAPI.findTeamFromPlayer(event.getPlayer().getUniqueId());
        if(team ==null){
            return;
        }
        setPrefix(event.getPlayer().getUniqueId(),null,team);
    }

    @EventHandler
    public void onTeamCreate(CreateTeamEvent event) {
        setPrefix(event.getPlayer().getUniqueId(), null, event.getTeam());
    }

    @EventHandler
    public void onTeamJoin(JoinTeamEvent event) {
        setPrefix(event.getPlayer().getUniqueId(), null, event.getTeam());
    }

    @EventHandler
    public void onTeamLeave(LeaveTeamEvent event) {
        setPrefix(event.getPlayer().getUniqueId(), event.getTeam(), null);
        if (event.getTeam().getCaptain().equals(event.getPlayer().getUniqueId())) {
            for (UUID member : event.getTeam().getMembers()) {
                setPrefix(member, event.getTeam(), null);
            }
        }
    }

    @EventHandler
    public void onPlayerQuit(PlayerQuitEvent event){
        map.remove(event.getPlayer().getUniqueId());
    }

    @EventHandler
    public void onPlayerChat(AsyncPlayerChatEvent event){
        //unfinished
    }

    private static void setPrefix(UUID p, ITeam lastTeam, ITeam newTeam) {
        if(newTeam==null) {
            map.remove(p);
            return;
        }
        map.put(p,prefix.replaceFirst("%team_name%",newTeam.getName()));
    }
}
